﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using CRMSimple.LogService.DataCache;
using CRMSimple.LogService.DataCache.Abstractions;
using CRMSimple.LogService.DataProtocol.Abstractions;

namespace CRMSimple.LogService.DataCacheExtensions.FileDataCache
{
    public abstract class FileDataCacheRoot : IDataCache
    {
        /// <summary>
        /// 获取应用程序跟路径
        /// </summary>
        public string BasePath {
            get { return AppDomain.CurrentDomain.BaseDirectory; }
        }
        public string SubPath { get; set; }
      
        public int CacheCount = 1;
        public string GetFile(string key)
        {
            //加入缓存的设置
            using (var Stream = this.CreateReadStream(key))
            {
                try
                {
                    return  this.StreamToString(Stream);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        

        /// <summary>
        /// 获取文件
        /// </summary>
        public string GetLine(string key,out long postion)
        {
            //加入缓存的设置
            using (var Stream = this.CreateReadStream(key))
            {
                try
                {
                    var content = this.StreamToStringLine(Stream, out postion);
                    //记录到配置文件，读取到了第几行
                    return content;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        /// <summary>
        /// 创建读取或者写入的流
        /// </summary>
        protected abstract Stream CreateReadStream(string key);
       
        /// <summary>
        /// 创建读取或者写入的流
        /// </summary>
        protected abstract Stream CreateWirteStream(DataParam data);
        /// <summary>
        /// 对数据进行加工
        /// </summary>
        protected abstract string GetMsg(DataParam data);
        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="message">接收到的数据</param>
        /// <param name="pubTime">接收到时间</param>
        public void Set(DataParam data)
        {

            //var Stream = this.CreateWirteStream(data);
            try
            {
                using (var Stream = this.CreateWirteStream(data))
                {
                    //if (Stream.CanWrite)
                    //{
                    var bytes = Encoding.UTF8.GetBytes(GetMsg(data));
                    Stream.Write(bytes, 0, bytes.Length);
                    //Stream.Flush();
                    //}
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
           
        }
        public abstract void Get(Action<DataParam> action);
    }
}
